package com.incar.chuxing.activity;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.bumptech.glide.Glide;
import com.incar.chuxing.R;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.Logger;
import com.incar.chuxing.widget.DragPhotoView;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;

public class PhotoViewActivity extends BaseActivity {

    @BindView(R.id.viewpager)
    ViewPager mViewPager;
    @BindView(R.id.back_button)
    ImageButton backButton;
    @BindView(R.id.radioGroup_viewPager)
    RadioGroup radioGroup;
    private RadioButton[] arrRadioButton = null;

    private DragPhotoView[] mPhotoViews;
    private ArrayList<String> mList = new ArrayList<>();
    private int toIndex;
    int mOriginLeft;
    int mOriginTop;
    int mOriginHeight;
    int mOriginWidth;
    int mOriginCenterX;
    int mOriginCenterY;
    private float mTargetHeight;
    private float mTargetWidth;
    private float mScaleX;
    private float mScaleY;
    private float mTranslationX;
    private float mTranslationY;

    @Override
    public int getLayoutId() {
        return R.layout.activity_photo_view;
    }

    @Override
    public void initView() {
        mList = getIntent().getStringArrayListExtra("pictures");
        toIndex = getIntent().getIntExtra("toIndex", 0);

        initViewPagerDots(mList.size());
        iniPhotoView();
        backButton.setOnClickListener(v -> finishWithAnimation());
    }


    public void initData() {

    }

    private void iniPhotoView() {
        mPhotoViews = new DragPhotoView[mList.size()];

        for (int i = 0; i < mPhotoViews.length; i++) {
            mPhotoViews[i] = (DragPhotoView) View.inflate(this, R.layout.item_photo_view, null);
            mPhotoViews[i].setOnTapListener(view -> finishWithAnimation());
            mPhotoViews[i].setOnExitListener((view, x, y, w, h) -> performExitAnimation(view, x, y, w, h));
            //Glide.with(getApplicationContext()).load(MyApplication.getInstance().getImageUrl() + mList.get(i)).thumbnail(0.1f).into(mPhotoViews[i]);
        }
        mViewPager.setOffscreenPageLimit(3);
        mViewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return mList.size();
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(mPhotoViews[position]);
                if (getIntent().getIntExtra("pictureType", 0) == 1) {
                    Glide.with(getApplicationContext()).load(new File(mList.get(position))).into(mPhotoViews[position]);
                } else {
                    Glide.with(getApplicationContext()).load(MyApplication.getInstance().getImageUrl() + mList.get(position)).thumbnail(0.1f).into(mPhotoViews[position]);
                }
                return mPhotoViews[position];
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(mPhotoViews[position]);
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }
        });


        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Logger.i("pagese", position + "");
                arrRadioButton[position].setChecked(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        mViewPager.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mViewPager.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                mOriginLeft = getIntent().getIntExtra("left", 0);
                mOriginTop = getIntent().getIntExtra("top", 0);
                mOriginHeight = getIntent().getIntExtra("height", 0);
                mOriginWidth = getIntent().getIntExtra("width", 0);
                mOriginCenterX = mOriginLeft + mOriginWidth / 2;
                mOriginCenterY = mOriginTop + mOriginHeight / 2;

                int[] location = new int[2];
                final DragPhotoView photoView = mPhotoViews[toIndex];
                photoView.getLocationOnScreen(location);

                mTargetHeight = (float) photoView.getHeight();
                mTargetWidth = (float) photoView.getWidth();
                mScaleX = (float) mOriginWidth / mTargetWidth;
                mScaleY = (float) mOriginHeight / mTargetHeight;

                float targetCenterX = location[0] + mTargetWidth / 2;
                float targetCenterY = location[1] + mTargetHeight / 2;

                mTranslationX = mOriginCenterX - targetCenterX;
                mTranslationY = mOriginCenterY - targetCenterY;
                photoView.setTranslationX(mTranslationX);
                photoView.setTranslationY(mTranslationY);

                photoView.setScaleX(mScaleX);
                photoView.setScaleY(mScaleY);

                performEnterAnimation();
                photoView.setMinScale(mScaleX);
            }
        });

        if (getIntent().getIntExtra("pictureType", 0) == 1) {
            mViewPager.setCurrentItem(toIndex);
        }
    }


    /**
     * ===================================================================================
     * <p>
     * 底下是低版本"共享元素"实现   不需要过分关心  如有需要 可作为参考.
     * <p>
     * Code  under is shared transitions in all android versions implementation
     */

    private void performExitAnimation(final DragPhotoView view, float x, float y, float w, float h) {
        backButton.setVisibility(View.GONE);
        radioGroup.setVisibility(View.GONE);
        view.finishAnimationCallBack();
        float viewX = mTargetWidth / 2 + x - mTargetWidth * mScaleX / 2;
        float viewY = mTargetHeight / 2 + y - mTargetHeight * mScaleY / 2;
        view.setX(viewX);
        view.setY(viewY);

        float centerX = view.getX() + mOriginWidth / 2;
        float centerY = view.getY() + mOriginHeight / 2;

        float translateX = mOriginCenterX - centerX;
        float translateY = mOriginCenterY - centerY;


        ValueAnimator translateXAnimator = ValueAnimator.ofFloat(view.getX(), view.getX() + translateX);
        translateXAnimator.addUpdateListener(valueAnimator -> view.setX((Float) valueAnimator.getAnimatedValue()));
        translateXAnimator.setDuration(300);
        translateXAnimator.start();
        ValueAnimator translateYAnimator = ValueAnimator.ofFloat(view.getY(), view.getY() + translateY);
        translateYAnimator.addUpdateListener(valueAnimator -> view.setY((Float) valueAnimator.getAnimatedValue()));
        translateYAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {

            }

            @Override
            public void onAnimationEnd(Animator animator) {
                Logger.d("viewpager", "finish1");
                animator.removeAllListeners();
                AppManager.getAppManager().finishActivity(PhotoViewActivity.class);
                overridePendingTransition(0, 0);
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        translateYAnimator.setDuration(300);
        translateYAnimator.start();
    }

    private void finishWithAnimation() {
        backButton.setVisibility(View.GONE);
        radioGroup.setVisibility(View.GONE);
        ValueAnimator translateXAnimator = ValueAnimator.ofFloat(0, mTranslationX);
        translateXAnimator.addUpdateListener(valueAnimator -> mViewPager.setX((Float) valueAnimator.getAnimatedValue()));
        translateXAnimator.setDuration(300);
        translateXAnimator.start();

        ValueAnimator translateYAnimator = ValueAnimator.ofFloat(0, mTranslationY);
        translateYAnimator.addUpdateListener(valueAnimator -> mViewPager.setY((Float) valueAnimator.getAnimatedValue()));
        translateYAnimator.setDuration(300);
        translateYAnimator.start();

        ValueAnimator scaleYAnimator = ValueAnimator.ofFloat(1, mScaleY);
        scaleYAnimator.addUpdateListener(valueAnimator -> mViewPager.setScaleY((Float) valueAnimator.getAnimatedValue()));
        scaleYAnimator.setDuration(300);
        scaleYAnimator.start();

        ValueAnimator scaleXAnimator = ValueAnimator.ofFloat(1, mScaleX);
        scaleXAnimator.addUpdateListener(valueAnimator -> mViewPager.setScaleX((Float) valueAnimator.getAnimatedValue()));

        scaleXAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {

            }

            @Override
            public void onAnimationEnd(Animator animator) {
                Logger.d("viewpager", "finish2");
                animator.removeAllListeners();
                AppManager.getAppManager().finishActivity(PhotoViewActivity.class);
                overridePendingTransition(0, 0);
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        scaleXAnimator.setDuration(300);
        scaleXAnimator.start();
    }

    private void performEnterAnimation() {
        final DragPhotoView photoView = mPhotoViews[toIndex];
        ValueAnimator translateXAnimator = ValueAnimator.ofFloat(photoView.getX(), 0);
        translateXAnimator.addUpdateListener(valueAnimator -> photoView.setX((Float) valueAnimator.getAnimatedValue()));
        translateXAnimator.setDuration(300);
        translateXAnimator.start();

        ValueAnimator translateYAnimator = ValueAnimator.ofFloat(photoView.getY(), 0);
        translateYAnimator.addUpdateListener(valueAnimator -> photoView.setY((Float) valueAnimator.getAnimatedValue()));
        translateYAnimator.setDuration(300);
        translateYAnimator.start();

        ValueAnimator scaleYAnimator = ValueAnimator.ofFloat(mScaleY, 1);
        scaleYAnimator.addUpdateListener(valueAnimator -> photoView.setScaleY((Float) valueAnimator.getAnimatedValue()));
        scaleYAnimator.setDuration(300);
        scaleYAnimator.start();

        ValueAnimator scaleXAnimator = ValueAnimator.ofFloat(mScaleX, 1);
        scaleXAnimator.addUpdateListener(valueAnimator -> photoView.setScaleX((Float) valueAnimator.getAnimatedValue()));
        scaleXAnimator.setDuration(300);
        scaleXAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                backButton.setVisibility(View.VISIBLE);
                radioGroup.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        scaleXAnimator.start();
    }

    @Override
    public void onBackPressed() {
        finishWithAnimation();
    }


    //初始化viewPager指示器
    private void initViewPagerDots(int count) {
        if (count == 1) {
            return;
        }
        radioGroup.removeAllViews();
        arrRadioButton = null;
        arrRadioButton = new RadioButton[count];
        for (int i = 0; i < count; i++) {
            RadioButton radioButton = new RadioButton(this);
            radioButton.setPadding(15, 0, 15, 0);
            radioButton.setButtonDrawable(R.drawable.dots);
            radioGroup.addView(radioButton);
            arrRadioButton[i] = radioButton;
        }
        if (arrRadioButton.length != 0) {
            arrRadioButton[0].setChecked(true);
        }
    }
}
